<?php

    #-------------------------------------------------------------#
	# This file is part of the Tekuna MVC Microframework for PHP. #
	# (c) 2009 Niels Jäckel <niels.jaeckel@tekuna.org>            #
	# Please visit http://tekuna.org/ for more information.       #
	#                                                             #
	# This software is licensed under the MIT License. Please     #
	# view the LICENSE file for the full text of this license.    #
    #-------------------------------------------------------------#


	Tekuna :: load('org.tekuna.core.application.TekunaLanguageChooser');


	/**
	 * The default language chooser implementation. The language is selected
	 * based on the information about the accepted client languages and the
	 * available application configuration languages. If the client accepts
	 * only languages that are not supported by the application, the default
	 * application language is returned.
	 */

	class DefaultLanguageChooser implements TekunaLanguageChooser {

		protected $objContext = NULL;


		/**
		 * DefaultLanguageChooser's constructor.
		 *
		 * @param TekunaApplicationContext $objContext the current application context.
		 */

		public function __construct(TekunaApplicationContext $objContext) {

			$this -> objContext = $objContext;
		}


		/**
		 * The implementation of the language selection algorithm.
		 * All accepted languages of the client are iterated. The first
		 * match with the application-supported languages is returned.
		 *
		 * If no match is found (the client accepts only languages that
		 * are not supported by the application configuration), the first
		 * entry of the supported languages is returned.
		 *
		 * @return string the selected language
		 */

		public function chooseLanguage() {

			// get the language arrays of the configuration and the client
			$arrApplicationLanguages = $this -> objContext -> getApplicationConfiguration() -> getLanguages();
			$arrClientLanguages = $this -> objContext -> getClientInformation() -> getAcceptedLanguages();

			// iterate the client's languages
			foreach ($arrClientLanguages as $sLanguage) {

				// if application provides the language, use the current language
				if (in_array($sLanguage, $arrApplicationLanguages)) {

					// use the matched language
					return $sLanguage;
				}
			}

			// if no match found, deliver the default language (first language entry)
			return $arrApplicationLanguages[0];
		}
	}
